$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_xzykjxmgl_m")
    const dgrid = $NG.getCmpApi("p_form_xzykjxmgl_d1")
    const config = {
        data_bak: []
    }

    if (page.oType == 'add' || page.oType == 'edit') {
        const quarter = getCurrentQuarter()
        const year = new Date().getFullYear()
        $NG.updateState((updater) => {
            updater.data.p_form_xzykjxmgl_m.setProps({
                u_nd: {
                    label: year,
                    value: year
                },
                u_jd: {
                    label: quarter.name,
                    value: quarter.value
                }
            })
        })
    }

    // setInterval(() => {
    //     const bigBox = dgrid.getRef().bodyRef.current
    //     const content = bigBox.childNodes[0]
    //     if (!content) {
    //         return
    //     }
    //     const box = bigBox.childNodes[0]
    //     if (!box) {
    //         return
    //     }
    //     box.childNodes.forEach(rowBox => {
    //         let lock = false
    //         rowBox.childNodes.forEach((dom,index) => {
    //             const rows = dgrid.getRows()
    //             if(rows[index].u_lock == '1'){
                    
    //             }
    //         })
    //     })
    // }, 1000)

    useBeforeClick(() => {
        const rows = dgrid.getRows()
        let lock = []
        rows.forEach((item, index) => {
            if (item.u_lock && item.checked) {
                lock.push(index + 1)
            }
        })
        if (lock.length !== 0) {
            $NG.alert("不能删除上个季度的数据！行号：" + lock.join('、'))
            return false
        }
    }, "deleterow")

    // 拉取相关季度明细
    useValuesChange(() => {
        getDetail()
    }, "p_form_xzykjxmgl_m.u_ssxm")
    useValuesChange(() => {
        getDetail()
    }, "p_form_xzykjxmgl_m.u_jd")

    useClick(() => {
        getFileId()
    }, "u_xz")

    useUpdateRow(({ args }) => {
        const row = args[0]
        if (row.u_lock) {
            $NG.alert("不能修改上季度数据！")
            config.data_bak.forEach(el => {
                if (el.u_lock == row.u_lock) {
                    Object.keys(row).forEach(item => {
                        if (item != 'u_lock') {
                            row[item] = el[item]
                        }
                    })
                }
            })
        }
        dgrid.refreshView()
    }, "p_form_xzykjxmgl_d1")

    function getDetail() {
        const jd = (Number(mstform.getItem("u_jd").getValue()) || 0) - 1
        console.log(jd, (Number(mstform.getItem("u_jd").getValue()) || 0))
        const phid_pc = mstform.getItem("u_ssxm").getValue()
        if (!jd || !phid_pc) return
        if (jd == '6870000000000382') return

        $NG.execServer("getTechProject", { phid_pc, jd }, (res) => {
            if (!res.count) return
            const datas = JSON.parse(res.data).reduce((value, item) => {
                item.extendObjects.u_lock = generateUUID()
                Object.keys(item.extendObjects).forEach(it => {
                    if (it.includes("exname")) {
                        item.extendObjects[it.replace("exname", "EXName")] = item.extendObjects[it]
                        delete item.extendObjects[it]
                    }
                })
                value.push(item.extendObjects)
                return value
            }, [])
            console.log(`要添加的数据`, datas);
            let temp = dgrid.getRows().filter(item => {
                if (!item.u_lock) {
                    return item
                }
            })
            temp = [...temp, ...datas]
            config.data_bak = [...temp]
            dgrid.clearRows().then(() => {
                console.log(`添加`, datas);
                dgrid.addRows(datas)
            })
        })
    }

    // // 获取上个季度
    // function getProjectPersonnelDetail() {
    //     // const phid_pc = mstform.getItem("phid_px")
    //     let jd = mstform.getItem("u_jd").getValue()
    //     const phid_pc = mstform.getItem("u_ssxm").getValue()
    //     console.log(`ceshi `, jd, phid_pc);
    //     if (!jd || !phid_pc || jd == '6870000000000382') return
    //     jd = (Number(jd) || 0) - 1
    //     $NG.execServer("getZyxmglByPhidPc", { jd, phid_pc }, (res) => {
    //         if (!res.count) return
    //         const datas = JSON.parse(res.data).reduce((value, item) => {
    //             item.extendObjects.u_lock = 1
    //             Object.keys(item.extendObjects).forEach(it => {
    //                 if (it.includes("exname")) {
    //                     item.extendObjects[it.replace("exname", "EXName")] = item.extendObjects[it]
    //                     delete item.extendObjects[it]
    //                 }
    //             })
    //             value.push(item.extendObjects)
    //             return value
    //         }, [])
    //         console.log(`要添加的数据`, datas);
    //         let temp = dgrid.getRows().filter(item => {
    //             if (item.u_lock == '0') {
    //                 return item
    //             }
    //         })
    //         // config.topData = [...datas]
    //         temp = [...temp, ...datas]
    //         dgrid.clearRows().then(() => {
    //             console.log(`添加`, datas);
    //             dgrid.addRows(datas)
    //         })
    //     })
    // }

    // 查询附件，找到附件的数量
    async function getFileId() {
        let asr = null
        await $NG.execServer("getAttachmentByasr", { code: '4003cc95-1601-41e5-a6e5-38b31b06d9b0' }, (res) => {
            if (res.count == 0) {
                asr = null
            } else {
                asr = JSON.parse(res.data)[0].extendObjects
            }
        })
        if (!asr) {
            $NG.alert("没有模板可以下载！")
            return
        }
        const origin = location.origin;
        const router = "/JFileSrv/reactAttach/download";
        const param = {
            asrFid: asr.asr_fid,
            asrName: asr.asr_name,
            busTypeCode: "drmb",
            loginId: "6870000000000016",
            orgId: "1",
            asrFilldt: asr.asr_filldt
        };

        const query = new URLSearchParams(param).toString();
        const url = `${origin}${router}?${query}`;

        try {
            // 1. fetch 请求，加上你需要的 header
            const res = await fetch(url, {
                method: "GET",
                headers: {
                    "Authorization": localStorage.getItem("Auth$#$i8$#$6.3sp1$#$lsz"),
                    "dbtoken": "0001", // 🔴 在这里加请求
                }
            });

            if (!res.ok) {
                throw new Error("下载失败: " + res.status);
            }
            // 从响应头解析文件名
            const disposition = res.headers.get("Content-Disposition");
            let filename = asr.asr_name
            if (disposition && disposition.includes("filename=")) {
                const match = disposition.match(/filename="?([^"]+)"?/);
                if (match.length > 1) {
                    filename = decodeURIComponent(match[1]);
                }
            }
            // 转 blob
            const blob = await res.blob();

            // 创建临时链接并下载
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = filename; // ✅ 指定文件名
            link.target = "_blank";
            document.body.appendChild(link);
            link.click();
            link.remove();

            setTimeout(() => URL.revokeObjectURL(link.href), 60000);
        } catch (err) {
            console.error(err);
            $NG.alert("下载出错啦！");
        }
        // const button = document.createElement('a');
        // button.style.display = 'none'
        // button.href = url
        // document.body.appendChild(button);
        // button.click()
    }

    function generateUUID() {
        // UUID v4的格式为：xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
        // 其中y位为8、9、A或B

        // 生成随机16进制数的辅助函数
        function randomHex() {
            // 生成0-0xffff的随机数，转换为16进制并补全4位
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
        }

        // 生成y位的值（8-11之间的随机数，16进制为8-b）
        const y = Math.floor(Math.random() * 4) + 8;

        return (
            randomHex() + '-' +
            randomHex() + '-' +
            '4' + randomHex().substring(1) + '-' +  // 第3段以4开头
            y.toString(16) + randomHex().substring(1) + '-' +  // 第4段以y开头
            randomHex() + randomHex()
        );
    }
    // 获取当前季度
    function getCurrentQuarter() {
        const date = new Date();
        const month = date.getMonth() + 1; // 月份从0开始，所以要加1
        let quarterName, quarterValue;

        if (month >= 1 && month <= 3) {
            quarterName = "第一季度";
            quarterValue = "6870000000000382";
        } else if (month >= 4 && month <= 6) {
            quarterName = "第二季度";
            quarterValue = "6870000000000383";
        } else if (month >= 7 && month <= 9) {
            quarterName = "第三季度";
            quarterValue = "6870000000000384";
        } else {
            quarterName = "第四季度";
            quarterValue = "6870000000000385";
        }

        return {
            name: quarterName,
            value: quarterValue
        };
    }
})